package com.exam.service.impl;

import com.exam.common.Constants;
import com.exam.dao.AppManagerDao;
import com.exam.service.AppManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AppManagerServiceImpl implements AppManagerService {

    @Autowired
    AppManagerDao appManagerDao;

    @Transactional
    @Override
    public String saveUser(HttpServletRequest request) {
        String appid = request.getParameter("appid");
        String userId = request.getParameter("userId");
        String channelId = request.getParameter("channelId");
        String requestId = request.getParameter("requestId");
        String imei = request.getParameter("imei");
        Map<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("userId", userId);
        param.put("channelId", channelId);
        param.put("requestId", requestId);
        param.put("imei", imei);
        String result = "ok";
        try {
            appManagerDao.deleteUserByIMEI(imei);
            appManagerDao.saveUser(param);
        } catch (Exception e) {
            result = "error";
            e.printStackTrace();
        }

        if("ok".equalsIgnoreCase(result)) {
            Constants.userInfo.put(imei, param);
        } else {
            if(Constants.userInfo.containsKey(imei)) {
                Constants.userInfo.remove(imei);
            }
        }
        return result;
    }

    @Override
    public List<Map<String, String>> getUserInfo() {
        return appManagerDao.getUserInfoList();
    }
}
